/**
 * This file is part of iSecurePasswords.
 *
 * iSecurePasswords is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * iSecurePasswords is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * iSecurePasswords. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Matthew MacGregor Created: 2012 iSecurePasswords, copyright 2013
 * Sudolink, LLC
 *
 */
package com.sudolink.isp.ui;

import com.sudolink.crypto.CryptoException;
import com.sudolink.cryptodata.CryptInfoBundle;
import com.sudolink.cryptodata.ISecureData;
import com.sudolink.cryptodata.SecureData;
import com.sudolink.isp.app.Application;
import com.sudolink.isp.cryptodata.SecureDataHelpers;
import com.sudolink.isp.media.HelperMethods;
import com.sudolink.isp.media.ResourceConstants;
import com.sudolink.isp.tasks.BackupTask;
import com.sudolink.isp.ui.locktimer.ICanBeLocked;
import com.sudolink.isp.ui.menu.CopyToClipboard;
import com.sudolink.isp.ui.menu.GoToUrl;
import java.awt.AWTEvent;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;


public final class MainWindow extends javax.swing.JFrame implements IRefreshData, ICanBeLocked {

    private final MainWindowManager mController;

    public MainWindow() {
        mController = new MainWindowManager(this);
        initComponents();
        refreshData();
        setIcon();
        registerUserInterfaceListeners();
        registerUserInteractionListeners();
        
    }
    
    @Override
    public void lock() {
        SwingUtilities.invokeLater(() -> {
            setVisible(false);
            Application.refreshLastUserInteractionTime();
        });
    }

    @Override
    public void unlock() {
        SwingUtilities.invokeLater(() -> {
            setVisible(true);
            Application.refreshLastUserInteractionTime();
        });
    }

    @Override
    public boolean isAvailable() {
        return true;
    }
    
    @Override
    public void refreshData() {
        String stringToMatch = tbSearch.getText();
        ISecureData[] list = Application.getSecureDataManager().getAll();
        list = mController.search(list, stringToMatch);
        mController.sort(list);
        tblElements.setModel(new SecureDataTableModel(list));
        resetTableColumns();
    }

    public void showDataVerificationWarning() {
        JOptionPane.showMessageDialog(this,
                "It looks like the database file has been changed \n"
                + "outside of this application. (This could be the \n"
                + "result of using syncing services such as Dropbox).\n"
                + "To prevent the possibility of data loss you will \n"
                + "need to restart the application.");
    }

    private void registerUserInteractionListeners() {
        Toolkit.getDefaultToolkit().addAWTEventListener((AWTEvent event) -> {
            if (event instanceof MouseEvent) {
                MouseEvent evt = (MouseEvent) event;
                if (evt.getID() == MouseEvent.MOUSE_CLICKED) {
                    Application.refreshLastUserInteractionTime();
                    mController.resetLock();
                }
            }
        }, AWTEvent.MOUSE_EVENT_MASK);
       
    }

    private void resetTableColumns() {
        int w = tblElements.getWidth();
        tblElements.getColumnModel().getColumn(0).setPreferredWidth((int) (w * 0.07));
        tblElements.getColumnModel().getColumn(0).setResizable(false);
        tblElements.getColumnModel().getColumn(1).setPreferredWidth((int) (w * 0.43));
        tblElements.getColumnModel().getColumn(2).setPreferredWidth((int) (w * 0.50));
    }

    private void registerUserInterfaceListeners() {
        tblElements.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                //For Mac OS Platform (Unix?)
                if (e.isPopupTrigger()) {
                    doPop(e);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                //For Windows Platform
                if (e.isPopupTrigger()) {
                    doPop(e);
                }
            }

            private void doPop(MouseEvent e) {
                JPopupMenu menu = new JPopupMenu();

                // Get the position of the click
                final int x = e.getX();
                final int y = e.getY();

                // Verify that the click occured on the selected cell
                final int index = tblElements.getSelectedRow();
                final Rectangle bounds = tblElements.getBounds();    //.getCellBounds(index, index);

                CryptInfoBundle bundle = Application.getPrivateKeys();

                if (null != bounds && bounds.contains(x, y)) {
                    ISecureData element = (ISecureData) tblElements.getModel().getValueAt(index, -1);   //.getSelectedValue();
                    String url = element.get(ISecureData.URL, bundle);
                    GoToUrl goToUrl = new GoToUrl(url);
                    CopyToClipboard userNameMenu = new CopyToClipboard(
                            element.get(ISecureData.USERNAME, bundle),
                            "Copy User Name to Clipboard");
                    userNameMenu.setIcon(HelperMethods.getIconResource(ResourceConstants.USER_ICON));
                    CopyToClipboard passwordNameMenu = new CopyToClipboard(
                            element.get(ISecureData.PASSWORD, bundle),
                            "Copy Password to Clipboard");
                    passwordNameMenu.setIcon(HelperMethods.getIconResource(ResourceConstants.LOCK_ICON));
                    userNameMenu.willClearClipboard(false);
                    passwordNameMenu.willClearClipboard(true);
                    menu.add(goToUrl);
                    menu.add(userNameMenu);
                    menu.add(passwordNameMenu);
                    menu.show(e.getComponent(), x, y);
                }


            }
        });

        /*
         * Add listener to handle keystrokes in the search box.
         */
        tbSearch.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                refreshData();
            }

            @Override
            public void keyPressed(KeyEvent e) {
                refreshData();
            }

            @Override
            public void keyReleased(KeyEvent e) {
                refreshData();
            }
        });
    }

    private void setIcon() {
        Image image = Toolkit.getDefaultToolkit().getImage(ResourceConstants.KEY_ICON);
        setIconImage(image);
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnNewEntry = new javax.swing.JButton();
        btnDeleteEntry = new javax.swing.JButton();
        btnLock = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        panelSearch = new javax.swing.JPanel();
        lblSearch = new javax.swing.JLabel();
        tbSearch = new javax.swing.JTextField();
        btnClearSearch = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblElements = tblElements = new javax.swing.JTable() {
            public String getToolTipText(MouseEvent e) {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int rowIndex = rowAtPoint(p);
                int colIndex = columnAtPoint(p);
                int realColumnIndex = convertColumnIndexToModel(colIndex);
                ISecureData data = (ISecureData) getValueAt(rowIndex, -1);
                if (realColumnIndex == 0) {
                    if( SecureDataHelpers.isPasswordExpired( data ) ) {
                        tip = "You should consider changing this password.";
                    }
                }
                return tip;
            }
        };
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        menuItem_ExportToJson = new javax.swing.JMenuItem();
        menuItem_ImportFromJson = new javax.swing.JMenuItem();
        menuTools = new javax.swing.JMenu();
        itemChangeMasterPassword = new javax.swing.JMenuItem();
        menuItem_changeUnlockPasscode = new javax.swing.JMenuItem();
        menuItem_ShowArchivedItems = new javax.swing.JCheckBoxMenuItem();
        menuAbout = new javax.swing.JMenu();
        menuItemAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("iSecurePasswords");
        setBackground(new java.awt.Color(185, 209, 234));

        jPanel1.setBackground(new java.awt.Color(204, 204, 204));

        btnNewEntry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/list-add.png"))); // NOI18N
        btnNewEntry.setText("New");
        btnNewEntry.setMaximumSize(null);
        btnNewEntry.setMinimumSize(null);
        btnNewEntry.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewEntryActionPerformed(evt);
            }
        });

        btnDeleteEntry.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/list-remove.png"))); // NOI18N
        btnDeleteEntry.setText("Delete");
        btnDeleteEntry.setMaximumSize(null);
        btnDeleteEntry.setMinimumSize(null);
        btnDeleteEntry.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteEntryEntryActionPerformed(evt);
            }
        });

        btnLock.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/lock.png"))); // NOI18N
        btnLock.setText("Lock");
        btnLock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLockActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnLock, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDeleteEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnNewEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNewEntry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDeleteEntry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnLock))
                .addContainerGap())
        );

        jPanel2.setBackground(new java.awt.Color(185, 209, 234));

        panelSearch.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblSearch.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblSearch.setText("Search");

        btnClearSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/cross.png"))); // NOI18N
        btnClearSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearSearchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelSearchLayout = new javax.swing.GroupLayout(panelSearch);
        panelSearch.setLayout(panelSearchLayout);
        panelSearchLayout.setHorizontalGroup(
            panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSearchLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tbSearch)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClearSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panelSearchLayout.setVerticalGroup(
            panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSearchLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSearch)
                    .addComponent(tbSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnClearSearch))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        tblElements.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        tblElements.setModel(new SecureDataTableModel(Application.getSecureDataManager().getAll())

        );
        tblElements.setGridColor(new java.awt.Color(204, 204, 204));
        tblElements.setRowHeight(20);
        tblElements.setRowMargin(2);
        tblElements.setSelectionBackground(new java.awt.Color(153, 255, 153));
        tblElements.setSelectionForeground(new java.awt.Color(0, 0, 0));
        tblElements.setShowVerticalLines(false);
        tblElements.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblElementsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblElements);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuFile.setText("File");

        menuItem_ExportToJson.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/edit-redo.png"))); // NOI18N
        menuItem_ExportToJson.setText("Export to JSON");
        menuItem_ExportToJson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItem_ExportToJsonActionPerformed(evt);
            }
        });
        menuFile.add(menuItem_ExportToJson);

        menuItem_ImportFromJson.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/edit-undo.png"))); // NOI18N
        menuItem_ImportFromJson.setText("Import from JSON");
        menuItem_ImportFromJson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItem_ImportFromJsonActionPerformed(evt);
            }
        });
        menuFile.add(menuItem_ImportFromJson);

        jMenuBar1.add(menuFile);

        menuTools.setText("Tools");

        itemChangeMasterPassword.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/lock.png"))); // NOI18N
        itemChangeMasterPassword.setText("Change Master Password");
        itemChangeMasterPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemChangeMasterPasswordActionPerformed(evt);
            }
        });
        menuTools.add(itemChangeMasterPassword);

        menuItem_changeUnlockPasscode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/key.png"))); // NOI18N
        menuItem_changeUnlockPasscode.setText("Change Screenlock Key");
        menuItem_changeUnlockPasscode.setToolTipText("");
        menuItem_changeUnlockPasscode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItem_changeUnlockPasscodeActionPerformed(evt);
            }
        });
        menuTools.add(menuItem_changeUnlockPasscode);

        menuItem_ShowArchivedItems.setText("Show Archived Items");
        menuItem_ShowArchivedItems.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItem_ShowArchivedItemsActionPerformed(evt);
            }
        });
        menuTools.add(menuItem_ShowArchivedItems);

        jMenuBar1.add(menuTools);

        menuAbout.setText("About");

        menuItemAbout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/sudolink/isp/media/help.png"))); // NOI18N
        menuItemAbout.setText("About iSecurePasswords");
        menuItemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemAboutActionPerformed(evt);
            }
        });
        menuAbout.add(menuItemAbout);

        jMenuBar1.add(menuAbout);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewEntryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewEntryActionPerformed

        if (Application.isDataVerificationSignatureValid()) {
            mController.addElement(this);
            tbSearch.setText("");
            refreshData();
        } else {
            this.showDataVerificationWarning();
        }

    }//GEN-LAST:event_btnNewEntryActionPerformed

    private void btnDeleteEntryEntryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteEntryEntryActionPerformed
        if (Application.isDataVerificationSignatureValid()) {
            int index = tblElements.getSelectedRow();
            SecureData sde = (SecureData) tblElements.getValueAt(index, -1);

            if (sde != null) {
                try {
                    mController.deleteElement(sde);
                    refreshData();
                } catch (IOException | CryptoException ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            this.showDataVerificationWarning();
        }

    }//GEN-LAST:event_btnDeleteEntryEntryActionPerformed

    private void menuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemAboutActionPerformed
        JOptionPane.showMessageDialog(this, "iSecurePasswords "
                + "\nCopyright 2012 Sudolink, LLC"
                + "\nCoded by Matthew MacGregor"
                + "\nVersion " + Application.getApplicationVersion());
    }//GEN-LAST:event_menuItemAboutActionPerformed

    private void itemChangeMasterPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemChangeMasterPasswordActionPerformed
        new BackupTask().run();
        PasswordChanger pwChanger = new PasswordChanger(this, this);
        pwChanger.setVisible(true);
    }//GEN-LAST:event_itemChangeMasterPasswordActionPerformed

    private void btnClearSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearSearchActionPerformed
        if (!tbSearch.getText().trim().isEmpty()) {
            tbSearch.setText("");
            refreshData();
        }
    }//GEN-LAST:event_btnClearSearchActionPerformed

    private void menuItem_ExportToJsonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_ExportToJsonActionPerformed
        JSONExportForm jef = new JSONExportForm(this, true);
        jef.setVisible(true);
    }//GEN-LAST:event_menuItem_ExportToJsonActionPerformed

    private void menuItem_ImportFromJsonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_ImportFromJsonActionPerformed
        JSONImportForm jief = new JSONImportForm(this, true);
        jief.setUICallback(new UICallback() {
            @Override
            public void actionPerformed(String value) {
                MainWindow.this.refreshData();
            }
        });
        jief.setVisible(true);
    }//GEN-LAST:event_menuItem_ImportFromJsonActionPerformed

    private void menuItem_changeUnlockPasscodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_changeUnlockPasscodeActionPerformed
        //Pop up an input box with text ( What is your name ? )  
        String key = JOptionPane.showInputDialog(null,
                "<html>The application will lock itself if you haven't <br/> "
                + " interacted with it for a certain amount of time. <br/>"
                + "The default passcode is blank, but you can <br/>"
                + "configure it here. <br/>"
                + "  <br/> Enter an unlock key:</html>");
        if (key != null) {
            Application.setUnlockCode(key);
        }
    }//GEN-LAST:event_menuItem_changeUnlockPasscodeActionPerformed

    private void tblElementsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblElementsMouseClicked
        if (evt.getClickCount() > 1
                //Check to see that the left mouse button was clicked
                && (evt.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
            if (Application.isDataVerificationSignatureValid()) {
                int index = tblElements.getSelectedRow();
                // TODO: Fix to use interface for ISecureData
                SecureData e = (SecureData)  tblElements.getValueAt(index, -1); //elementList.getSelectedValue();
                mController.addElement(this, e);
            } else {
                showDataVerificationWarning();
            }
        }
    }//GEN-LAST:event_tblElementsMouseClicked

    private void menuItem_ShowArchivedItemsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_ShowArchivedItemsActionPerformed

        boolean showArchived = menuItem_ShowArchivedItems.isSelected();
        mController.setShowArchivedEntries(showArchived);
        refreshData();

    }//GEN-LAST:event_menuItem_ShowArchivedItemsActionPerformed

    private void btnLockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLockActionPerformed
        
//        this.setVisible(false);
        mController.lockAll();

        
        
    }//GEN-LAST:event_btnLockActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClearSearch;
    private javax.swing.JButton btnDeleteEntry;
    private javax.swing.JButton btnLock;
    private javax.swing.JButton btnNewEntry;
    private javax.swing.JMenuItem itemChangeMasterPassword;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblSearch;
    private javax.swing.JMenu menuAbout;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenuItem menuItemAbout;
    private javax.swing.JMenuItem menuItem_ExportToJson;
    private javax.swing.JMenuItem menuItem_ImportFromJson;
    private javax.swing.JCheckBoxMenuItem menuItem_ShowArchivedItems;
    private javax.swing.JMenuItem menuItem_changeUnlockPasscode;
    private javax.swing.JMenu menuTools;
    private javax.swing.JPanel panelSearch;
    private javax.swing.JTextField tbSearch;
    private javax.swing.JTable tblElements;
    // End of variables declaration//GEN-END:variables


}
